using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetEmployeesListQueryHandler : IRequestHandler<GetEmployeesListQuery, ApiPaging<EmployeeDto>>
	{
		private readonly IBaseRepository<Employee> _repository;

		public GetEmployeesListQueryHandler(IBaseRepository<Employee> repository)
		{
			_repository = repository;
		}

		public async Task<ApiPaging<EmployeeDto>> Handle(GetEmployeesListQuery request, CancellationToken cancellationToken)
		{
			var query = _repository.GetAll().Where(x => !x.IsDeleted);
			if (!string.IsNullOrEmpty(request.NameKeyword)) query = query.Where(x => ((Employee)x).FullName.Contains(request.NameKeyword));
			if (!string.IsNullOrEmpty(request.WorkNo)) query = query.Where(x => ((Employee)x).WorkNo == request.WorkNo);
			if (request.DepartmentId.HasValue) query = query.Where(x => ((Employee)x).DepartmentId == request.DepartmentId);
			if (!string.IsNullOrEmpty(request.Role)) query = query.Where(x => ((Employee)x).Role == request.Role);

			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query
				.OrderByDescending(x => ((Employee)x).CreatedAt)
				.Skip((request.Page - 1) * request.Size)
				.Take(request.Size)
				.Select(x => (Employee)x)
				.Select(e => new EmployeeDto
				{
					EmployeeId = e.EmployeeId,
					UserName = e.UserName,
					FullName = e.FullName,
					WorkNo = e.WorkNo,
					DepartmentId = e.DepartmentId,
					Email = e.Email,
					Gender = e.Gender,
					Address = e.Address,
					Phone = e.Phone,
					IdCardNo = e.IdCardNo,
					Title = e.Title,
					Role = e.Role,
					IsActive = e.IsActive,
					CreatedAt = e.CreatedAt,
					UpdatedAt = e.UpdatedAt
				})
				.ToListAsync(cancellationToken);

			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<EmployeeDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
